<template>
  <div class="search-header">
    <div
      class="my-share"
      style="border-bottom: 1px solid #ccc; padding-bottom: 6px"
    >
      <div>
        <div style="font-weight: 600">分享笔记</div>
        <div style="padding-left: 10px; color: #7f7f7f">
          分享给我的{{ shareToMeTotalCount }}篇,&nbsp;&nbsp;我分享的{{
            shareToOtherTotalCount
          }}篇
        </div>
      </div>
      <el-input
        style="width: 200px"
        v-model="queryNote.keyword"
        placeholder="搜索..."
        @input="handleSearch"
      />
    </div>
    <div class="search">
      <div class="tabs-share">
        <span
          @click="handleChangeTab(2)"
          :class="currentIndex === 2 ? 'activeTab' : ''"
          >分享给我</span
        >
        <span
          @click="handleChangeTab(1)"
          :class="currentIndex === 1 ? 'activeTab' : ''"
          >我分享的</span
        >
      </div>
      <div class="sort-icons">
        <el-popover
          ref="popover"
          placement="left"
          :width="80"
          trigger="click"
          class="custom-popover"
        >
          <div
            class="btns"
            style="
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              gap: 4px;
            "
          >
            <el-button
              style="margin: 0 !important; border: none !important; width: 100%"
              class="sort-item"
              v-for="(item, index) in sortList"
              :key="index"
              :class="{
                active: currentId === item.id,
              }"
              :type="currentId === item.id ? 'primary' : 'default'"
              @click="toggleSort(item)"
            >
              {{ item.label }}
            </el-button>
          </div>
          <template #reference>
            <el-icon v-if="down" style="cursor: pointer; font-size: 24px">
              <Desc />
            </el-icon>
            <el-icon v-else style="cursor: pointer; font-size: 24px">
              <Asc />
            </el-icon>
          </template>
        </el-popover>
        <el-icon
          v-if="isCard"
          @click="isCard = !isCard"
          style="cursor: pointer; font-size: 24px"
        >
          <Menu />
        </el-icon>
        <el-icon
          v-else
          @click="isCard = !isCard"
          style="cursor: pointer; font-size: 24px"
        >
          <Toggle />
        </el-icon>
      </div>
    </div>
  </div>
  <div class="padding-10 note-box" v-loading="loading">
    <el-row :gutter="20" v-if="noteList.length && isCard" class="item-box">
      <template v-for="(item, index) in noteList" :key="index">
        <el-card
          v-if="item.set"
          style="
            width: 180px;
            height: 248px;
            border: none !important;
            cursor: pointer;
          "
          shadow="hover"
          @click="handleJumpEditNote(item)"
        >
          <template #header>
            <div
              class="header-btn"
              style="display: flex; flex-direction: column"
            >
              <div style="text-align: end">
                <el-popover
                  placement="bottom"
                  :width="100"
                  trigger="hover"
                  class="custom-popover"
                >
                  <template #reference>
                    <el-icon @click.stop="() => {}" style="cursor: pointer"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                  <div
                    class="btns-wrapper"
                    style="display: flex; flex-direction: column"
                  >
                    <el-button
                      v-for="(button, n) in handleReturnOperation(item)"
                      :key="n"
                      style="
                        margin: 0 !important;
                        border: none !important;
                        justify-content: flex-start;
                      "
                      @click="handleOpenNote(button, item)"
                    >
                      {{ button.label }}
                    </el-button>
                  </div>
                </el-popover>
              </div>
              <el-text
                line-clamp="1"
                style="text-align: start; align-self: flex-start"
                >{{ item.title }}</el-text
              >
            </div>
          </template>
          <div
            v-if="item.content && item.icon == 'Document'"
            class="content-w"
            style="width: 160px; height: 110px"
          >
            <el-text
              :innerHTML="replaceImg(item.content, '160', '120')"
              line-clamp="5"
              style="width: 160px; height: 110px"
            >
            </el-text>
          </div>
          <div
            style="
              width: 160px;
              height: 110px;
              display: flex;
              align-items: center;
              justify-content: center;
            "
            v-else-if="item.icon == 'FlowChart'"
          >
            <el-icon style="font-size: 44px" color="#409eff">
              <FlowChart />
            </el-icon>
          </div>
          <div
            style="
              width: 160px;
              height: 110px;
              display: flex;
              align-items: center;
              justify-content: center;
            "
            v-else-if="item.icon == 'Xmind'"
          >
            <el-icon style="font-size: 44px" color="#409eff">
              <Xmind />
            </el-icon>
          </div>
          <div
            v-else
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              height: 110px;
              cursor: pointer;
            "
          >
            <el-icon :size="56" color="#409efe"><Document /></el-icon>
          </div>
          <div class="tags" style="height: 60px">
            <el-space
              wrap
              class="tag-wrapper"
              v-if="(item.tags && item.tags.length) || true"
            >
              <el-text type="primary" line-clamp="2" style="width: fit-content">
                <el-tag
                  round
                  v-for="(tag, i) in item.label"
                  :key="i"
                  type="primary"
                  size="small"
                  style="margin: 0 2px 0 0; padding: 2px 6px"
                  >{{ tag.label_name }}</el-tag
                ></el-text
              >
            </el-space>
          </div>
          <template #footer>
            <div
              class="footer-wrapper"
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <span>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  placement="top-start"
                  v-if="currentIndex == 2"
                >
                  <template #content>
                    <el-icon><Avatar /></el-icon> 来自{{ item.user_name }}的分享
                  </template>
                  <el-icon>
                    <ShareInner />
                  </el-icon>
                </el-tooltip>
                <el-icon v-show="currentIndex == 1">
                  <Share />
                </el-icon>
              </span>
              <span>
                {{
                  item.updated_at &&
                  new Date(item.updated_at).toLocaleDateString()
                }}
              </span>
            </div>
          </template>
        </el-card>
        <el-card
          style="
            width: 180px;
            height: 248px;
            border: none !important;
            cursor: pointer;
          "
          @click="handleJumpEditNote(item)"
          v-else
        >
          <div class="invalid-wrapper">
            <el-text style="width: 100%" truncated>
              {{ item.title }}
            </el-text>
            <div style="text-align: center; height: 140px">
              <el-icon size="128" color="#537def"><Warning /></el-icon>
            </div>
            <p style="height: 20px">无效分享地址</p>
            <p style="color: #7f7f7f; font-size: 12px; margin-top: 10px">
              对方停止分享或该分享不存在
            </p>
            <el-icon v-if="currentIndex === 1">
              <Share />
            </el-icon>
            <el-icon v-else>
              <ShareInner />
            </el-icon>
          </div>
        </el-card>
      </template>
    </el-row>
    <List :list="noteList" v-if="!isCard"></List>
    <el-empty description="暂无分享" v-if="!loading && !noteList.length" />
    <pagination
      v-if="noteList.length"
      :total="noteListTotal"
      v-model:page="queryNote.page"
      v-model:limit="queryNote.limit"
      @pagination="getList"
    />

    <el-dialog
      v-model="editTitleVisible"
      draggable
      overflow
      title="修改标题"
      width="500"
      destroy-on-close
      @close="resetForm(ruleFormRef)"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="fileForm"
        label-width="auto"
        size="default"
        :rules="rules"
      >
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="fileForm.name" placeholder="请输入标题" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          <el-button
            type="primary"
            :loading="modifyFileLoading"
            @click="submitForm(ruleFormRef)"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <Modal v-model="deleteFile" @confirm="deleteNoteConfirm"></Modal>
  <LabelModal
    v-model:visible="labelVisible"
    :rowData="appendParentData"
  ></LabelModal>

  <MoveNoteModal
    v-model="moveVisible"
    :appendParentData="appendParentData"
  ></MoveNoteModal>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import Modal from './components/deleteNoteModal.vue'
import LabelModal from './components/labelModal.vue'
import MoveNoteModal from './components/moveNoteModal.vue'
import {
  httpUpdatefolder,
  httpDeleteNoteBook,
  httpCreateNote,
  httpGetShareListWithDiffType,
  httpDeleteShareToMyNote,
} from '@/api/note.js'
import { downloadFile, debounce, replaceImg } from '@/utils/tools.ts'
import Pagination from '@/components/pagination/index.vue'
import Desc from '@/icons/Desc.vue'
import Asc from '@/icons/Asc.vue'
import Menu from '@/icons/Menu.vue'
import Toggle from '@/icons/Toggle.vue'
import List from './components/List.vue'
import Share from '@/icons/Share.vue'
import ShareInner from '@/icons/ShareInner.vue'
import { MoreFilled } from '@element-plus/icons-vue'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
import { useRouter, useRoute } from 'vue-router'
import useNote from '@/hooks/useNote'
import { ElMessage, ElMessageBox } from 'element-plus'
import { asBlob } from 'html-docx-js-typescript'
import useUserStore from '@/stores/user.js'
const userStore = useUserStore()
const { info } = storeToRefs(userStore)
const router = useRouter()
// const route = useRoute()
const noteState = useNoteStore()
// const {  } = storeToRefs(noteState)
const { FlowChart, Xmind } = useNote()
const ruleFormRef = ref()
const modifyFileLoading = ref(false)
const fileForm = reactive({
  name: '',
}) // 重命名
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入标题名称',
      trigger: ['blur', 'change'],
    },
  ],
})
const down = ref(true)
const isCard = ref(true)
const currentId = ref(2)

const moreFilledbuttons = [
  {
    id: '1',
    label: '重命名',
  },
  {
    id: '2',
    label: '移动到',
  },
  {
    id: '3',
    label: '复制',
  },
  {
    id: '4',
    label: '粘贴',
  },
  {
    id: '5',
    label: '删除',
  },
  {
    id: '6',
    label: '导出word',
  },
  {
    id: '7',
    label: '新窗口打开',
  },
  {
    id: '8',
    label: '关联标签',
  },
]
const otherList = [
  // {
  //   id: '1',
  //   label: '重命名',
  // },
  {
    id: '5',
    label: '删除',
  },
  {
    id: '6',
    label: '导出word',
  },
  {
    id: '7',
    label: '新窗口打开',
  },
  {
    id: '9',
    label: '保存到我的笔记',
  },
]
const currentIndex = ref(2)
const isOwner = ref(true) // TODO: 是否是自己的笔记
const hasPermission = ref(true) // TODO: 判断是否有权限
const editTitleVisible = ref(false)
const deleteFile = ref(false)
const loading = ref(false)
const noteList = ref([])
const noteListTotal = ref(0)
const selectSortItem = ref()
const handleJumpEditNote = (item) => {
  if ((!item.set && currentIndex.value === 1) || item.set) {
    router.push('/file/share-edit/' + item.id)
  }
}
const appendParentData = ref({}) // 右击选中的节点
const textToCopy = ref({}) // 复制的内容
const noteTypes = ['Document', 'Xmind', 'FlowChart']
const labelVisible = ref(false) //关联标签弹窗
const moveVisible = ref(false)
const queryNote = reactive({
  page: 1,
  limit: 20,
  // folder_id: 0,
  keyword: '',
  sort_order: 1,
  share_type: 2,
})
// isOwner.value = !!(queryNote.share_type === 1)
const handleReturnOperation = (item) => {
  // TODO:判断是否是自己的笔记
  isOwner.value = item.user_info_id === info.value.user_info_id
  if (item.icon == 'Document') {
    if (isOwner.value) {
      return moreFilledbuttons
    } else if (hasPermission.value) {
      return otherList
    } else {
      return []
    }
  } else {
    if (isOwner.value) {
      return moreFilledbuttons.filter((x) => x.id !== '6')
    } else if (hasPermission.value) {
      return otherList.filter((x) => x.id !== '6')
    } else {
      return []
    }
  }
}
const handleChangeTab = debounce((item) => {
  currentIndex.value = item
  queryNote.share_type = item
  getList()
}, 300)
const MapNoteOperations = {
  1: (item) => {
    // 重命名
    editTitleVisible.value = true
    fileForm.name = item.title
  },
  2: () => {
    // 移动
    moveVisible.value = true
  },
  3: (item) => {
    // 复制
    copyToClipboard(item)
  },
  4: async () => {
    // 粘贴
    if (noteTypes.includes(textToCopy.value.icon)) {
      const res = await httpCreateNote({
        folder_id: textToCopy.value.parent_id,
        title: '',
        content: textToCopy.value.content,
        icon: textToCopy.value.icon,
        label_id_list: textToCopy.value.label || [],
      })
      if (res) {
        ElMessage.success('粘贴成功')
        // TODO: 刷新快捷方式和文件夹列表
        getList()
        noteState.getFolderListData()
        noteState.getShortCutList()
      } else {
        ElMessage.error('粘贴失败')
      }
    }
  },
  5: () => {
    // 删除
    // 不是本人的笔记
    if (appendParentData.value.user_info_id !== info.value.user_info_id) {
      ElMessageBox.confirm('确认删除分享吗?', '删除分享', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const result = await httpDeleteShareToMyNote({
            fd_id: appendParentData.value.id,
          })
          if (result) {
            ElMessage.success('删除成功')
            queryNote.page = 1
            getList()
          } else {
            ElMessage.error('删除失败')
          }
        })
        .catch(() => {})
    } else {
      // 是本人的笔记
      deleteFile.value = true
    }
  },
  6: async (item) => {
    // 导出word
    const data = await asBlob(item.content, {
      orientation: 'landscape',
      margins: { top: 100 },
    })
    if (item.icon == 'Document') {
      downloadFile(data, item.title)
    }
  },
  7: (item) => {
    // 新窗口打开
    let href
    if (item.icon == 'Document') {
      href = router.resolve({
        path: `/file/doc/${item.id}`,
      }).href
    } else if (item.icon == 'Xmind') {
      href = router.resolve({
        path: `/file/mindmap/${item.id}`,
      }).href
    } else {
      href = router.resolve({
        path: `/file/drawio/${item.id}`,
      }).href
    }
    window.open(href, '_blank')
  },
  8: () => {
    // 关联标签
    labelVisible.value = true
  },
  9: async (item) => {
    // 保存到我的笔记
    const res = await httpCreateNote({
      folder_id: 0,
      title: '',
      content: item.content,
      icon: item.icon,
      label_id_list: [],
    })
    if (res) {
      ElMessage.success('保存到我的笔记成功')
      noteState.getFolderListData()
    } else {
      ElMessage.error('保存失败')
    }
  },
}
const sortList = ref([
  {
    id: 1,
    label: '创建时间',
  },
  {
    id: 2,
    label: '更新时间',
  },
  {
    id: 3,
    label: '笔记名称',
  },
])
const mapSortFn = {
  1: () => {
    queryNote.sort_order = down.value ? 1 : 3
  },
  2: () => {
    queryNote.sort_order = down.value ? 1 : 4
  },
  3: () => {
    queryNote.sort_order = down.value ? 2 : 5
  },
}

const toggleSort = (item) => {
  if (currentId.value === item.id) {
    down.value = !down.value
  } else {
    currentId.value = item.id
    down.value = true
  }
  mapSortFn[item.id]()
  getList()
  selectSortItem.value = item
}
const handleOpenNote = async (btn, item) => {
  appendParentData.value = item
  MapNoteOperations[btn.id](item)
}
/**
 * 复制到粘贴板
 */
const copyToClipboard = async (content) => {
  if (queryNote.share_type == 2) {
    return
  }
  try {
    textToCopy.value = content
    await navigator.clipboard.writeText(JSON.stringify(textToCopy.value))
    ElMessage.success('复制成功')
  } catch (err) {
    console.error('复制失败', err)
  }
}
/**
 * 粘贴
 * @param {*} event
 */
const paste = (event) => {
  // TODO: 要根据权限去判断是否能复制粘贴
  if (queryNote.share_type == 2) {
    return
  }
  if (event.ctrlKey && event.key === 'v') {
    // 读取粘贴板
    navigator.clipboard.readText().then(
      async (text) => {
        if (text) {
          try {
            let data = JSON.parse(text)
            if (noteTypes.includes(data.icon)) {
              const res = await httpCreateNote({
                folder_id: data.parent_id,
                title: '',
                content: data.content,
                icon: data.icon,
                label_id_list: data.label || [],
              })
              if (res) {
                ElMessage.success('粘贴成功')
                getList()
                noteState.getFolderListData()
                noteState.getShortCutList()
              } else {
                ElMessage.error('粘贴失败')
              }
            }
          } catch (error) {
            console.error('粘贴板内容不是json格式', error)
          }
        }
      },
      (err) => {
        console.error('无法读取粘贴板内容：', err)
      },
    )
  }
}

const shareToMeTotalCount = ref(0)
const shareToOtherTotalCount = ref(0)
const initFirst = ref(1)
const getList = async () => {
  loading.value = true
  noteList.value = []
  noteListTotal.value = 0
  let data = {
    ...queryNote,
  }
  const response = await httpGetShareListWithDiffType(data).catch(() => null)
  loading.value = false
  if (!response) return
  const { list, total } = response
  noteList.value = list
  noteListTotal.value = total
  if (initFirst.value == 1) {
    shareToMeTotalCount.value = total
    initFirst.value++
  }
}
onMounted(async () => {
  getList()
  const res = await httpGetShareListWithDiffType({
    page: 1,
    limit: 1,
    keyword: '',
    sort_order: 1,
    share_type: 1,
  }).catch(() => null)
  const { total } = res
  shareToOtherTotalCount.value = total
  document.addEventListener('keydown', paste)
})
const handleSearch = debounce(() => {
  queryNote.page = 1
  getList()
}, 800)

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (appendParentData.value.title == fileForm.name) {
        editTitleVisible.value = false
        return
      }
      const res = await httpUpdatefolder({
        folder_id: appendParentData.value.id,
        name: fileForm.name,
      })
      if (res) {
        editTitleVisible.value = false
        queryNote.page = 1
        getList()
        noteState.getFolderListData()
        noteState.getShortCutList()
      }
    }
  })
}
const resetForm = (formEl) => {
  if (!formEl) return
  editTitleVisible.value = false
  formEl.resetFields()
  fileForm.name = ''
}

const deleteNoteConfirm = async () => {
  if (appendParentData.value.user_info_id === info.value.user_info_id) {
    let res = await httpDeleteNoteBook({
      detail_id: appendParentData.value.id,
    })
    if (res) {
      ElMessage.success('删除成功')
      queryNote.page = 1
      getList()
      noteState.getFolderListData()
      noteState.getShortCutList()
    } else {
      ElMessage.error('删除失败')
    }
  } else {
    // 不是本人笔记
  }

  deleteFile.value = false
}
</script>
<style scoped lang="scss">
.search-header {
  width: 100%;
  padding: 0 10px;
  .my-share {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .search {
    padding: 4px 0;
    display: flex;
    justify-content: space-between;
    .activeTab {
      color: var(--el-color-primary);
      font-weight: 600;
    }
    .tabs-share {
      display: flex;
      gap: 10px;
      span {
        font-size: 14px;
        cursor: pointer;
        &:hover {
          color: var(--el-color-primary-light-3);
          font-weight: 600;
        }
      }
    }
    .sort-icons {
      display: flex;
      gap: 4px;
      cursor: pointer;
    }
  }
}
.note-box {
  height: calc(100vh - 100px);
  overflow: auto;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .item-box {
    padding-left: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    :deep(.el-card__header) {
      padding: 0px 10px 0 !important;
      border: none !important;
    }
    :deep(.el-card__body) {
      padding: 0 10px !important;
      border: none !important;
    }
    :deep(.el-card__footer) {
      padding: 0 10px !important;
      border: none !important;
      text-align: end;
    }
  }
}
/* 滚动条样式 */
::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/* 滑块样式 */
::-webkit-scrollbar-thumb {
  background-color: #9f9f9f;
  border-radius: 10px;
}
/* 滚动条轨道样式 */
::-webkit-scrollbar-track {
  background-color: #fcfcfc;
  border-radius: 10px;
}
</style>
